import serial
import time

def send_serial_commands():
    """
    给COM126串口发送命令:
    T0到T0.5(每0.5秒增加0.01)
    保持1秒
    发送T0结束
    """
    try:
        # 打开串口
        ser = serial.Serial('COM126', 115200, timeout=1)
        print(f"已连接到串口: {ser.name}")
        
        # 发送从T0到T0.5的命令，每次增加0.01
        value = 0.0
        while value <= 0.5:
            command = f"T{value:.2f}\n"
            ser.write(command.encode())
            print(f"已发送: {command.strip()}")
            value += 0.01
            time.sleep(0.2)  # 每0.5秒发送一次
            
        # 保持1秒
        print("保持1秒...")
        time.sleep(1)
        
        # 发送T0结束
        end_command = "T0\n"
        ser.write(end_command.encode())
        print("已发送结束命令: T0")
        
        # 关闭串口
        ser.close()
        print("串口已关闭")
        
    except serial.SerialException as e:
        print(f"串口错误: {e}")
    except Exception as e:
        print(f"发生错误: {e}")

if __name__ == "__main__":
    send_serial_commands()